package com.xzy.e;

import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * 说明：
 *
 * @author xzy
 * @date 2021/11/28 21:04
 */
public class Main {

    public static void main(String[] args) {
        // 1、通过BeanDefinition定义FactoryBean
        AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();
        beanDefinition.setBeanClass(PersonFactoryBean.class);

        // 2、向Spring容器注册BeanDefinition
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        applicationContext.registerBeanDefinition("person", beanDefinition);
        applicationContext.refresh();

        // 3、从Spring容器获取Bean
        PersonService personService = (PersonService) applicationContext.getBean("person");
        PersonFactoryBean personFactoryBean = (PersonFactoryBean) applicationContext.getBean("&person");


        /*
         * FactoryBean是非常特殊的Bean：Spring容器会根据FactoryBean的BeanDefinition创建两个Bean，
         * 一个是FactoryBean本身，一个是FactoryBean中getObject()方法返回的Bean。
         */
        System.out.println(personService);
        System.out.println(personFactoryBean);

        System.out.println(applicationContext.getBean(PersonService.class));
        System.out.println(applicationContext.getBean(PersonFactoryBean.class));
    }
}
